var gulp = require('gulp') // 引入定义工具
var del = require('del') // 文件（夹）删除
var browserSync = require('browser-sync') // 动态刷新
var rev = require('gulp-rev') //- 对文件名加MD5后缀
var revCollector = require('gulp-rev-collector') //- 路径替换
var sass = require('gulp-sass') // 编译scss 为 css
var cleanCss = require('gulp-clean-css') // css压缩
var postcss = require('gulp-postcss') //js处理css
var autoprefixer = require('autoprefixer') //postcss插件：浏览器前缀补全
var posthtml = require('gulp-posthtml') //js处理html
var includehtml = require('posthtml-include') //posthtml插件：组件化Hhtml
// 定义路径
var path = {
  css: ['./src/css/*.scss', './src/css/*.css'],
  js: './src/js/*.js',
  html: './src/*.html',
  image: './src/images/*',
  rev: './rev/*/*.json'
}
gulp.task('clean', function() {
  del.sync(['dist/'])
})
gulp.task('js', function() {
  gulp
    .src(path.js)
    .pipe(rev()) //- 文件名加MD5后缀
    .pipe(gulp.dest('./dist/js'))
    .pipe(rev.manifest()) //- 生成一个rev-manifest.json
    .pipe(gulp.dest('./rev/js')) //- 将 rev-manifest.json 保存到 rev 目录内
    .pipe(browserSync.stream())
})

gulp.task('css', function() {
  var plugins = [autoprefixer({ browsers: ['last 3 version'] })]
  return gulp
    .src(path.css)
    .pipe(rev()) //- 文件名加MD5后缀
    .pipe(sass())
    .pipe(postcss(plugins))
    .pipe(cleanCss())
    .pipe(gulp.dest('./dist/css'))
    .pipe(rev.manifest()) //- 生成一个rev-manifest.json
    .pipe(gulp.dest('./rev/css')) //- 将 rev-manifest.json 保存到 rev 目录内
    .pipe(browserSync.stream())
})
gulp.task('image', function() {
  return gulp
    .src('./src/images/*.{png,jpg,gif,ico}')
    .pipe(rev())
    .pipe(gulp.dest('./dist/images'))
    .pipe(rev.manifest())
    .pipe(gulp.dest('./rev/images'))
})

gulp.task('html', function() {
  var plugins = [
    includehtml({
      root: './src',
      encoding: 'utf-8'
    })
  ]
  gulp
    .src(path.html)
    .pipe(posthtml(plugins))
    .pipe(gulp.dest('./dist'))
    .pipe(browserSync.stream())
})
gulp.task('revCss', ['css', 'image'], function() {
  return gulp
    .src(['rev/**/*.json', './dist/css/*.css'])
    .pipe(
      revCollector({
        replaceReved: true,
        dirReplacements: {
          '/images/': '/images/'
        }
      })
    )
    .pipe(gulp.dest('./dist/css'))
})
gulp.task('rev', ['html', 'revCss'], function() {
  return gulp
    .src([path.rev, './dist/*.html']) //- 读取 rev-manifest.json 文件以及需要进行css名替换的文件
    .pipe(revCollector()) //- 执行文件内css名的替换
    .pipe(gulp.dest('./dist')) //- 替换后的文件输出的目录
    .pipe(browserSync.stream())
})
gulp.task('server', ['clean', 'js', 'rev'], function() {
  browserSync.init({
    server: {
      baseDir: './dist'
    },
    port: 3000
  })
  // 监听变化
  gulp.watch(path.html, ['rev'])
  gulp.watch(path.js, ['js', 'rev'])
  gulp.watch(path.css, ['css', 'rev'])
  gulp.watch(path.image, ['image', 'rev'])
})
